package com.formiaomiao.demain.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.formiaomiao.demain.R;
import com.formiaomiao.demain.activity.DemainCommentActivity;
import com.formiaomiao.demain.activity.DemainUserActivity;
import com.formiaomiao.demain.adapter.DataRecycleAdapter;
import com.formiaomiao.demain.base.BaseFragment;
import com.formiaomiao.demain.base.BaseUrl;
import com.formiaomiao.demain.model.DemainBean;
import com.formiaomiao.demain.ui.PublishWindow;
import com.formiaomiao.demain.util.MessageEvent;
import com.formiaomiao.demain.util.PreferenceUtils;
import com.formiaomiao.demain.util.PreferenceValues;
import com.formiaomiao.demain.util.StaticValues;
import com.formiaomiao.demain.util.ToastUtils;
import com.formiaomiao.demain.weight.LoadingDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.StoreHouseHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.sharesdk.onekeyshare.OnekeyShare;

public class DemainAllFragment extends BaseFragment
        implements DataRecycleAdapter.onLongItemClickListener {
    @BindView(R.id.storeHouseHeader)
    StoreHouseHeader storeHouseHeader;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    Unbinder unbinder;

    RefreshHeader refreshHeader;

    DemainBean demainBean = new DemainBean();

    List<DemainBean.DataBean.ListBean> beanList = new ArrayList<>();
    DataRecycleAdapter recycleAdapter;

    PublishWindow publishWindow;
    PopupWindow pops;

    LoadingDialog dialog;

    int pages = 1;

    private PopupWindow pop;
    private TextView tv_share;
    private TextView tv_delete;
    private LinearLayout ll_cancle_layout;

    public static DemainAllFragment newInstance() {
        Bundle args = new Bundle();
        DemainAllFragment fragment = new DemainAllFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_demain_layout, container, false);
        unbinder = ButterKnife.bind(this, v);
        DataInit();
        return v;
    }

    private void DataInit() {
        EventBus.getDefault().register(this);
        dialog = new LoadingDialog(getActivity());
        pops = new PopupWindow(getActivity());
        publishWindow = new PublishWindow(getActivity(),pops);
        refreshHeader = refreshLayout.getRefreshHeader();
        refreshLayout.setFooterHeight(300);
        refreshLayout.setFooterInsetStart(50);
        if (PreferenceUtils.getString(getActivity(), PreferenceValues.REFRESHWORD) != null &&
                !PreferenceUtils.getString(getActivity(), PreferenceValues.REFRESHWORD).equals("")) {
            ((StoreHouseHeader) refreshHeader).initWithString(PreferenceUtils.getString(getActivity(), PreferenceValues.REFRESHWORD));
        } else {
            ((StoreHouseHeader) refreshHeader).initWithString("DEMAIN");
        }
        recycleAdapter = new DataRecycleAdapter(getActivity(), beanList);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(recycleAdapter);
        recycleAdapter.setOnLongItemClickListener(this);
        EventInit();
        DemainDataInit(1);
    }

    private void EventInit() {
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                DemainDataInit(++pages);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pages = 1;
                DemainDataInit(pages);
            }
        });
    }

    /**
     * 显示选择pop
     *
     * @param parent
     */
    public void showOperationPopWindow(View parent, final int i) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.popw_alert_select_operation, null);
        tv_share = view.findViewById(R.id.tv_share);
        tv_delete = view.findViewById(R.id.tv_delete);
        tv_share.setVisibility(View.GONE);
        if (beanList.get(i).getIduser() == StaticValues.userid) {
            tv_delete.setVisibility(View.VISIBLE);
        } else {
            tv_delete.setVisibility(View.GONE);
        }
        ll_cancle_layout = view.findViewById(R.id.ll_cancle_layout);
        // 设置SelectPicPopupWindow的View
        pop = new PopupWindow(getActivity());
        pop.setContentView(view);
        // 设置SelectPicPopupWindow弹出窗体的宽
        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        // 设置SelectPicPopupWindow弹出窗体的高
        pop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        pop.setFocusable(true);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        // 设置SelectPicPopupWindow弹出窗体的背景
        pop.setBackgroundDrawable(dw);
        // 获取当前打开的界面的 父View
        // mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
        view.setOnTouchListener(new View.OnTouchListener() {

            @SuppressLint("ClickableViewAccessibility")
            public boolean onTouch(View v, MotionEvent event) {
                pop.dismiss();
                return true;
            }
        });

        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DemainDeleteInit(i);
            }
        });

        ll_cancle_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pop != null) {
                    pop.dismiss();
                }
            }
        });
        pop.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void showShare(int index) {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题，微信、QQ和QQ空间等平台使用
        oks.setTitle("Demain");
        // text是分享文本，所有平台都需要这个字段
        oks.setText(beanList.get(index).getContent());
        oks.setImageUrl("https://www.bmob.cn/uploads/attached/app/logo/20180711/9ede3748-9162-09e3-6b97-10c6a39565fc.png");
        // url在微信、微博，Facebook等平台中使用
        oks.setUrl("http://demain.bmob.site/");
        // 启动分享GUI
        oks.show(getActivity());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    @Override
    public void longItemClickListener(View v, int i) {
        showOperationPopWindow(v, i);
    }

    @Override
    public void headItemClickListener(View v, int i) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), DemainUserActivity.class);
        intent.putExtra("id", beanList.get(i).getIduser());
        intent.putExtra("name", beanList.get(i).getUserBean().getNickName());
        intent.putExtra("head", beanList.get(i).getUserBean().getUserHead());
        intent.putExtra("username", beanList.get(i).getUserBean().getUserName());
        startActivity(intent);
    }

    @Override
    public void shareItemClickListener(View v, int i) {
        showShare(i);
    }

    @Override
    public void msgItemClickListener(View v, final int i) {
        if (beanList.get(i).getMsgcount() == 0) {
            publishWindow.showPicPopWindow(recyclerView);
            publishWindow.setOnPublishClickListener(new PublishWindow.PublishClickListener() {
                @Override
                public void onPublishClickListener(View v, String data) {
                    PublishDataInit(i,beanList.get(i).getDataid(),data);
                }
            });
        } else {
            Intent intent = new Intent();
            intent.setClass(getActivity(), DemainCommentActivity.class);
            intent.putExtra("userid", beanList.get(i).getIduser());
            intent.putExtra("name", beanList.get(i).getUserBean().getNickName());
            intent.putExtra("head", beanList.get(i).getUserBean().getUserHead());
            intent.putExtra("username", beanList.get(i).getUserBean().getUserName());
            intent.putExtra("time", beanList.get(i).getContentDate());
            intent.putExtra("data", beanList.get(i).getContent());
            intent.putExtra("demainid", beanList.get(i).getDataid());
            ArrayList<String> imglist = new ArrayList<>();
            for (int j = 0; j < beanList.get(i).getImgBean().size(); j++) {
                imglist.add(beanList.get(i).getImgBean().get(j).getUrl());
            }
            intent.putStringArrayListExtra("imgs", imglist);
            startActivity(intent);
        }
    }

    @Override
    public void likeItemClickListener(View v, int i) {
        int type = -1;
        if (beanList.get(i).getIslike() == 0) {
            type = 1;
        } else {
            type = 0;
        }
        LikeingInit(i, type);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent msg) {
        if (msg.getMessage().equals("上传数据")) {
            dialog.show();
            DemainDataInit(1);
        } else if (msg.getMessage().equals("下拉刷新")) {
            if (PreferenceUtils.getString(getActivity(), PreferenceValues.REFRESHWORD) != null &&
                    !PreferenceUtils.getString(getActivity(), PreferenceValues.REFRESHWORD).equals("")) {
                ((StoreHouseHeader) refreshHeader).initWithString(PreferenceUtils.getString(getActivity(), PreferenceValues.REFRESHWORD));
            } else {
                ((StoreHouseHeader) refreshHeader).initWithString("DEMAIN");
            }
        }
    }

    /**
     * 获取所有动态
     */
    public void DemainDataInit(final int page) {
        HttpParams params = new HttpParams();
        params.put("id", StaticValues.userid);
        params.put("pageNum", page);
        params.put("pageSize", 10);
        OkGo.<String>post(BaseUrl.DEMAINALLSELECT).
                headers("Authorization", PreferenceUtils.getString(getActivity(), PreferenceValues.TOKEN)).params(params)
                .tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (page == 1) {
                    beanList.clear();
                }
                demainBean = gson.fromJson(response.body(), DemainBean.class);
                if (demainBean.getCode() == 200) {
                    beanList.addAll(demainBean.getData().getList());
                    recycleAdapter.notifyDataSetChanged();
                } else {
                    ToastUtils.show(getActivity(), demainBean.getMsg());
                }
                dialog.dismiss();
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();

            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dialog.dismiss();
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
            }
        });
    }

    /**
     * 删除动态操作
     *
     * @param index
     */
    public void DemainDeleteInit(final int index) {
        dialog.show();
        HttpParams params = new HttpParams();
        params.put("id", beanList.get(index).getDataid());
        OkGo.<String>post(BaseUrl.DEMAINDELETE).tag(this).headers("Authorization", PreferenceUtils.getString(getActivity(), PreferenceValues.TOKEN))
                .params(params).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body().contains("200")) {
                    ToastUtils.show(getActivity(), "删除成功");
                    pop.dismiss();
                    beanList.remove(index);
                    recycleAdapter.notifyDataSetChanged();
                } else {
                    ToastUtils.show(getActivity(), "删除失败");
                    pop.dismiss();
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dialog.dismiss();
            }
        });
    }

    /**
     * 点赞
     */
    private void LikeingInit(final int i, final int type) {
        dialog.show();
        HttpParams params = new HttpParams();
        params.put("likeid", beanList.get(i).getDataid());
        params.put("userid", StaticValues.userid);
        params.put("type", type);
        OkGo.<String>post(BaseUrl.LIKE)
                .headers("Authorization", PreferenceUtils.getString(getActivity(), PreferenceValues.TOKEN))
                .params(params).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body().contains("200")) {
                    if (beanList.get(i).getIslike() == 0) {
                        beanList.get(i).setIslike(1);
                        beanList.get(i).setLikecount(beanList.get(i).getLikecount() + 1);
                    } else {
                        beanList.get(i).setIslike(0);
                        beanList.get(i).setLikecount(beanList.get(i).getLikecount() - 1);
                    }
                    recycleAdapter.notifyDataSetChanged();
                } else {
                    ToastUtils.show(getActivity(), "操作失败");
                }
            }

            @Override
            public void onError(Response<String> response) {

            }

            @Override
            public void onFinish() {
                dialog.dismiss();
            }
        });
    }

    private void PublishDataInit(final int index, String topicid, String data) {
        dialog.show();
        HttpParams params = new HttpParams();
        params.put("topicid", topicid);
        params.put("content", data);
        params.put("fromuid", StaticValues.userid);
        OkGo.<String>post(BaseUrl.INSERTCOMMENT)
                .headers("Authorization", PreferenceUtils.getString(getActivity(), PreferenceValues.TOKEN))
                .params(params).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body().contains("200")) {
                    ToastUtils.show(getActivity(), "评论成功");
                    beanList.get(index).setMsgcount(beanList.get(index).getMsgcount() + 1);
                    recycleAdapter.notifyDataSetChanged();
                    if (pops != null) {
                        pops.dismiss();
                    }
                } else {
                    ToastUtils.show(getActivity(), "评论失败");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }

            @Override
            public void onFinish() {
                dialog.dismiss();
            }
        });
    }
}
